<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" :rules="inputRules" label-width="68px">
      <el-form-item style="width:240px" prop="payNo">
        <div>交易单号</div>
        <el-input v-model.trim="param.payNo" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px" prop="orderNo">
        <div>关联订单号</div>
        <el-input v-model.trim="param.orderNo" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>结算日期</div>
        <el-date-picker v-model="param.payDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:120px">
        <div>结算类型</div>
        <el-select v-model="param.payType" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.payTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:120px">
        <div>结算流向</div>
        <el-select v-model="param.payDirection" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.payDirections" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:120px">
        <div>结算币种</div>
        <el-select v-model="param.currency" clearable style="width:100%" placeholder="请选择">
          <el-option label="人民币" value="CNY" />
          <el-option label="美元" value="USD" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <div>
      <!-- <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"></cz-tages> -->
      <span style="margin-top: 10px;float: right;">
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" size="small" style="width:80px" :disabled="!selection.length" round @click="" plain>导出</el-button>
      </span>
      <Table ref="tableRef" :allId="allId" :isAllCheck="isAllCheck" v-bind="table" @pageChange="onTablePageChange" @showInvoice="showInvoice" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
      </Table>
    </div>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible">
      <div v-for="(item,index) in param.payUrl" :key="index">
        <!-- <iframe v-if="item && item.url" :src="item.url" width="800" height="600"></iframe> -->
        <pdfViewer :url="item.url"></pdfViewer>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import Table from '@/components/table'
import { getTable, getPayData, addPay } from '@/api/pay/index'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {Plus, Delete,Promotion,Edit,Message,Download,ChatDotRound} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'


const param = reactive({
  payDirections: [
    { value: 1, label: '收入' },
    { value: -1, label: '支出' },
  ],
  currency:'',
  payType:'',
  payTypes: [//5-租箱款 10-回调箱款 15-购箱款
    { value: 5, label: '租箱款' },
    { value: 10, label: '回调箱款' },
    { value: 25, label: '租箱退款' }
  ],

  radio: 0,
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],

  invoiceTypeList: [{ value: 5, label: '增值税普通发票' }, { value: 10, label: '增值税专用发票' }],
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'releaseRentId', colWidth: '220', title: 'releaseRentId', type: 'text', isCheck: true },
    // { key: 'id', colWidth: '220', title: 'ID', type: 'text', isCheck: true },5-租箱款 10-回调箱款  15-购箱款
    { key: 'payNo', colWidth: '200', title: '交易单号', type: 'text', isCheck: true },
    { key: 'payOrderNo', colWidth: '200', title: '关联订单号', type: 'text', isCheck: true },
    { key: 'actualPayAmount', colWidth: '80', title: '结算金额', type: 'add', currency: 'currency', isCheck: true },
    { key: 'payType', colWidth: '100', title: '结算类型', type: 'filter', filter: { 5: '租箱款', 10: '回调箱款', 15: '购箱款' }, isCheck: true },
    { key: 'payDirection', colWidth: '100', title: '结算流向', type: 'filter', filter: { '-1': '支出', 1: '收入' }, isCheck: true },
    { key: 'businessName', colWidth: '150', title: '结算单位', type: 'text', isCheck: true },
    { key: 'payDate', colWidth: '150', title: '结算时间', type: 'dateTime', isCheck: true },
    { key: 'paymentMethod', colWidth: '160', title: '支付方式', type: 'filter', filter: { 5: '对公转账', 10: '在线支付' }, isCheck: true }, //5-对公转账  10-在线支付
    { key: 'operate', colWidth: '100', title: '电子回执单', type: 'operate', isCheck: true, buttons: [{ icon: 'List', command: 'showInvoice', }] },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

const inputRules = {
  // payNo: [{ pattern: /^[A-Z0-9]+$/, message: "请输入大写字母、数字", trigger: "blur" }],
  // orderNo:[{ pattern: /^[A-Z0-9]+$/, message: "请输入大写字母、数字", trigger: "blur" }]
};

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    payNo: param.payNo?.trim().toUpperCase(),
    orderNo: param.orderNo?.trim().toUpperCase(),
    // payType: param.payType,
    payTypes: [5,10,25],
    currency: param.currency,
    payDirection: param.payDirection,
  };
  if(param.payType){
    data.payTypes.length = 0
    data.payTypes.push(param.payType)
  }
  if (param.payDate) {
    data.beginPayDate = param.payDate[0]
    data.endPayDate = param.payDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getTable(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.data.map((item: any) => {
      if (!item.payOrder) return
      // item.payOrder = JSON.parse(item.payOrder)
      // item.payOrderNo = item.payOrder[0].orderNo
      
      item.payOrder = JSON.parse(item.payOrder)
      let payOrderStr = '' 
      item.payOrder.forEach((item: any) => {
        if(payOrderStr == ""){
          payOrderStr = item.orderNo
        }else{
          payOrderStr = payOrderStr + ' / ' + item.orderNo
        }
      })
      item.payOrderNo = payOrderStr


    })
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}
// 重置
function handleReSet() {
  param.payNo = null
  param.orderNo = null
  param.payDate = null
  param.payType = null
  param.payDirection = null
  getTableData()
}

//查看回执单
const showInvoice = (row: any) => {
  if (!row.payUrl) return ElMessage.error('chengzhi 未发现回执单url')
  param.payUrl = JSON.parse(row.payUrl)
  // param.payUrl = [{ url: 'http://47.122.3.254:9000/default/template/发票文件.pdf' }]
  param.dialogVisible = true
}

//选中项 
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})




const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getTable({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


</script>

<style scoped></style>